package com.ja.openchat.views;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.text.Editable;
import android.text.InputType;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.ViewModelProviders;

import com.ja.openchat.R;
import com.ja.openchat.ui.chat.ConversationFragment;
import com.ja.openchat.ui.chat.MessageViewModel;
import com.ja.openchat.ui.chat.audio.AudioRecorderPanel;
import com.ja.openchat.ui.chat.ext.core.ConversationExtension;
import com.ja.openchat.ui.contact.ContactChooseActivity;
import com.lqr.emoji.EmotionLayout;
import com.lqr.emoji.IEmotionExtClickListener;
import com.lqr.emoji.IEmotionSelectedListener;
import com.lqr.emoji.LQREmotionKit;
import com.lqr.emoji.MoonUtils;
import com.lqr.emoji.ViewPagerFixed;
import com.zy.openchat.Constants;
import com.zy.openchat.core.manager.ChatDraftManager;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.model.group.LocalMessageInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.message.Draft;
import com.zy.openchat.core.model.message.Mention;
import com.zy.openchat.core.model.message.MentionSpan;
import com.zy.openchat.core.model.message.MessageInfo;
import com.zy.openchat.core.model.message.TextEntity;
import com.zy.openchat.core.model.sticker.StickerInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.SPUtils;
import com.zy.openchat.core.model.config.AppConfigInfo;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import pub.devrel.easypermissions.EasyPermissions;

public class ConversationInputPanel extends FrameLayout implements IEmotionSelectedListener {

    @BindView(R.id.inputContainerLinearLayout)
    LinearLayout inputContainerLinearLayout;
    @BindView(R.id.disableInputTipTextView)
    TextView disableInputTipTextView;

    @BindView(R.id.audioImageView)
    ImageView audioImageView;
    @BindView(R.id.audioButton)
    AppCompatButton audioButton;
    @BindView(R.id.editText)
    public EditText editText;
    @BindView(R.id.emotionImageView)
    ImageView emotionImageView;
    @BindView(R.id.extImageView)
    ImageView extImageView;
    @BindView(R.id.sendButton)
    TextView sendButton;
    @BindView(R.id.seekBar_open_readTime)
    Switch seekBarOpenReadTime;
    @BindView(R.id.seekBar)
    SeekBar seekBar;
    @BindView(R.id.read_time_set_complete)
    TextView readTimeSetComplete;
    @BindView(R.id.read_time_title)
    TextView readTimeTitle;
    @BindView(R.id.chat_read_layout)
    LinearLayout chatReadLayout;


    @BindView(R.id.emotionContainerFrameLayout)
    KeyboardHeightFrameLayout emotionContainerFrameLayout;
    @BindView(R.id.emotionLayout)
    EmotionLayout emotionLayout;
    @BindView(R.id.extContainerContainerLayout)
    KeyboardHeightFrameLayout extContainerFrameLayout;

    @BindView(R.id.conversationExtViewPager)
    ViewPagerFixed extViewPager;

    @BindView(R.id.refRelativeLayout)
    RelativeLayout refRelativeLayout;
    @BindView(R.id.refEditText)
    EditText refEditText;
    @BindView(R.id.chatReadBtn)
    ImageView chatReadBtn;

    public ConversationExtension extension;
    private ChatInfo conversation;
    private MessageViewModel messageViewModel;
    private InputAwareLayout rootLinearLayout;
    private Fragment fragment;
    private FragmentActivity activity;
    private AudioRecorderPanel audioRecorderPanel;

    private long lastTypingTime;
    private String draftString;
    private static final int TYPING_INTERVAL_IN_SECOND = 10;
    private static final int MAX_EMOJI_PER_MESSAGE = 50;
    private int messageEmojiCount = 0;

    private OnConversationInputPanelStateChangeListener onConversationInputPanelStateChangeListener;
    private int currentProgress;

    public ConversationInputPanel(@NonNull Context context) {
        super(context);
    }

    public ConversationInputPanel(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);

    }

    public ConversationInputPanel(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public ConversationInputPanel(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);

    }

    public void setOnConversationInputPanelStateChangeListener(OnConversationInputPanelStateChangeListener onConversationInputPanelStateChangeListener) {
        this.onConversationInputPanelStateChangeListener = onConversationInputPanelStateChangeListener;
    }

    public void bind(FragmentActivity activity, InputAwareLayout rootInputAwareLayout) {

    }

    public void setupConversation(ChatInfo conversation) {
        this.conversation = conversation;
        this.extension.bind(this.messageViewModel, conversation);
        if(conversation!=null){
            AppConfigInfo configInfo = AppConfigInfo.getAppWithoutLoginConfigInfo();
            configInfo.enabled_destroy_after_reading = true;
            if(configInfo==null||configInfo.enabled_destroy_after_reading){
                chatReadBtn.setVisibility(View.VISIBLE);
            }else{
                chatReadBtn.setVisibility(View.GONE);
            }
        }else{
            chatReadBtn.setVisibility(View.GONE);
        }
        setDraft();
    }

    private MessageInfo quoteInfo;

    public void quoteMessage(MessageInfo message) {
        this.quoteInfo = message;
        refRelativeLayout.setVisibility(VISIBLE);
        refEditText.setText(UserInfo.userDisplayName(message.sender_user_id()) + ": " + message.toString());
    }

    private void clearQuoteMessage() {
        if (refRelativeLayout.getVisibility() == VISIBLE) {
            refEditText.setText("");
            refRelativeLayout.setVisibility(GONE);
        }
        quoteInfo = null;
    }

    public void disableInput(String tip) {
        closeConversationInputPanel();
        inputContainerLinearLayout.setVisibility(GONE);
        disableInputTipTextView.setVisibility(VISIBLE);
        disableInputTipTextView.setText(tip);
    }

    public void enableInput() {
        inputContainerLinearLayout.setVisibility(VISIBLE);
        disableInputTipTextView.setVisibility(GONE);
    }

    public void onDestroy() {
        this.extension.onDestroy();
        emotionLayout.destory();
    }

    public void init(Fragment fragment, InputAwareLayout rootInputAwareLayout) {
        LayoutInflater.from(getContext()).inflate(R.layout.conversation_input_panel, this, true);
        ButterKnife.bind(this, this);

        this.activity = fragment.getActivity();
        this.fragment = fragment;
        this.rootLinearLayout = rootInputAwareLayout;

        this.extension = new ConversationExtension(fragment, this, extViewPager);

        // emotion
        emotionLayout.setEmotionAddVisiable(false);
        emotionLayout.setEmotionSettingVisiable(false);

        // audio record panel
        audioRecorderPanel = new AudioRecorderPanel(getContext());
        audioRecorderPanel.setRecordListener(new AudioRecorderPanel.OnRecordListener() {
            @Override
            public void onRecordSuccess(String audioFile, int duration) {
                //发送文件
                File file = new File(audioFile);
                if (file.exists()) {
                    if(conversation.isGroupSendChat()){
                        LocalMessageInfo.setResultIntent(activity
                                ,((ConversationFragment)fragment).getGroupSendInfo()
                                ,LocalMessageInfo.buildMediaLocalMessage(
                                        TelegramManager.MessageType.MessageType_Audio,
                                        audioFile,messageViewModel.getBurnAfterCountDown(),
                                        0,0,
                                        duration));
                    }else{
                        messageViewModel.sendAudioFile(conversation, Uri.parse(audioFile), duration);
                    }

                }
            }

            @Override
            public void onRecordFail(String reason) {
                Toast.makeText(activity, reason, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onRecordStateChanged(AudioRecorderPanel.RecordState state) {
                if (state == AudioRecorderPanel.RecordState.START) {
//                    TypingMessageContent content = new TypingMessageContent(TypingMessageContent.TYPING_VOICE);
//                    messageViewModel.sendMessage(conversation, content);
                }
            }
        });

        // emotion
        emotionLayout.setEmotionSelectedListener(this);
        emotionLayout.setEmotionExtClickListener(new IEmotionExtClickListener() {
            @Override
            public void onEmotionAddClick(View view) {
                Toast.makeText(activity, "add", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onEmotionSettingClick(View view) {
                Toast.makeText(activity, "setting", Toast.LENGTH_SHORT).show();
            }
        });

        messageViewModel = ViewModelProviders.of(fragment).get(MessageViewModel.class);

        audioButton.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        audioButton.setText(getResources().getString(R.string.loosen_to_send));
                        break;
                    case MotionEvent.ACTION_UP:
                        audioButton.setText(getResources().getString(R.string.please_to_talk));

                        break;
                    default:
                }
                return false;
            }
        });

        if(SPUtils.getBoolean(activity,Constants.SPU_FOR_ENTER_KEY_FOR_SEND,true)){
            editText.setSingleLine(true);
            editText.setImeOptions(EditorInfo.IME_ACTION_SEND);
            editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_NORMAL);
            editText.setMaxLines(Integer.MAX_VALUE);
            editText.setHorizontallyScrolling(false);
            editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
                @Override
                public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                        if (actionId == EditorInfo.IME_ACTION_UNSPECIFIED ||actionId == EditorInfo.IME_ACTION_SEND||(event!=null&&event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                            sendMessage();
                            return true;
                        }
                        return false;
                }
            });
        }
    }

    @OnClick(R.id.extImageView)
    void onExtImageViewClick() {
        if (audioButton.getTag() != null) {
            return;
        }
        if (rootLinearLayout.getCurrentInput() == extContainerFrameLayout) {
            hideConversationExtension();
            rootLinearLayout.showSoftkey(editText);
        } else {
            showConversationExtension();
        }
    }

    @OnClick(R.id.emotionImageView)
    void onEmotionImageViewClick() {

        if (audioRecorderPanel.isShowingRecorder()) {
            return;
        }
        if (rootLinearLayout.getCurrentInput() == emotionContainerFrameLayout) {
            hideEmotionLayout();
            rootLinearLayout.showSoftkey(editText);
        } else {
            hideAudioButton();
            showEmotionLayout();
        }
    }

    @OnClick(R.id.clearRefImageButton)
    void onClearRefImageButtonClick() {
        clearQuoteMessage();
        updateConversationDraft();
    }

    @OnTextChanged(value = R.id.editText, callback = OnTextChanged.Callback.TEXT_CHANGED)
    void onInputTextChanged(CharSequence s, int start, int before, int count) {
        if (activity.getCurrentFocus() == editText) {
            if (conversation.isGroup()) {
                if (before == 0 && count == 1&&s.charAt(start) == '@') {
                    mentionGroupMember(false);
                }else if(start+count>=2){
                    String text = editText.getText().toString();
                    if(!TextUtils.isEmpty(text)&&text.length()>= Constants.DM_TEXT_LENGTH&&Constants.DM_TEXT.equalsIgnoreCase(text.substring(text.length()-Constants.DM_TEXT_LENGTH,text.length()))){
                        mentionGroupMember(true);
                    }
                }
                // delete
                if (before == 1 && count == 0) {
                    Editable text = editText.getText();
                    MentionSpan[] spans = text.getSpans(0, text.length(), MentionSpan.class);
                    if (spans != null) {
                        for (MentionSpan span : spans) {
                            if (text.getSpanEnd(span) == start && text.getSpanFlags(span) == Spanned.SPAN_INCLUSIVE_EXCLUSIVE) {
                                text.delete(text.getSpanStart(span), text.getSpanEnd(span));
                                text.removeSpan(span);
                                break;
                            } else if (start >= text.getSpanStart(span) && start < text.getSpanEnd(span)) {
                                text.removeSpan(span);
                                break;
                            }
                        }
                    }
                }

                // insert
                if (before == 0 && count > 0) {
                    Editable text = editText.getText();
                    MentionSpan[] spans = text.getSpans(0, text.length(), MentionSpan.class);
                    if (spans != null) {
                        for (MentionSpan span : spans) {
                            if (start >= text.getSpanStart(span) && start < text.getSpanEnd(span)) {
                                text.removeSpan(span);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    private void mentionGroupMember(boolean isDm) {
        if(conversation!=null&&activity!=null){
            if(isDm){
                if(fragment!=null&&fragment instanceof ConversationFragment &&!((ConversationFragment)fragment).canDm()){
                    return;
                }
                ContactChooseActivity.startWithDmAtSomeone(activity,conversation.id,conversation.superGroupId());
            }else{
                ContactChooseActivity.startWithAtSomeone(activity,conversation.id,conversation.superGroupId());
            }

        }
    }

    @OnTextChanged(value = R.id.editText, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    void afterInputTextChanged(Editable editable) {
        if (editText.getText().toString().trim().length() > 0&&!audioButton.isShown()) {
            if (activity.getCurrentFocus() == editText) {
                notifyTyping();
            }
            sendButton.setVisibility(View.VISIBLE);
            audioImageView.setVisibility(View.GONE);
//            extImageView.setVisibility(View.GONE);
            chatReadBtn.setVisibility(View.GONE);
        } else {
            sendButton.setVisibility(View.GONE);
            audioImageView.setVisibility(View.VISIBLE);
//            extImageView.setVisibility(View.VISIBLE);
            AppConfigInfo configInfo = AppConfigInfo.getAppWithoutLoginConfigInfo();
            if(configInfo==null||configInfo.enabled_destroy_after_reading){
                chatReadBtn.setVisibility(View.VISIBLE);
            }else{
                chatReadBtn.setVisibility(View.GONE);
            }
        }
    }

    @OnClick(R.id.audioImageView)
    public void showRecordPanel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            String[] PERMISSIONS_BASIC = new String[]{Manifest.permission.RECORD_AUDIO};
            if (!EasyPermissions.hasPermissions(activity, PERMISSIONS_BASIC)) {
                EasyPermissions.requestPermissions(activity,
                        String.format(activity.getResources().getString(R.string.permission_basic_tip), activity.getResources().getString(R.string.app_name)),
                        100, PERMISSIONS_BASIC);
                return;
            }
        }

        if (audioButton.isShown()) {
            hideAudioButton();
            editText.requestFocus();
            rootLinearLayout.showSoftkey(editText);
        } else {
//            editText.clearFocus();
            showAudioButton();
            hideEmotionLayout();
            rootLinearLayout.hideSoftkey(editText, null);
            hideConversationExtension();
        }
    }
//    private int choosePosition = 0;
    @OnClick(R.id.chatReadBtn)
    public void showChatReading() {
        rootLinearLayout.hideSoftkey(editText, null);
        if(!chatReadLayout.isShown()){
            chatReadLayout.setVisibility(VISIBLE);
            if(messageViewModel.getCurrentProgress()>0){
                seekBarOpenReadTime.setChecked(true);
                seekBar.setProgress(messageViewModel.getCurrentProgress());
            }
        }else{
            chatReadLayout.setVisibility(GONE);
        }
        readTimeSetComplete.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                chatReadLayout.setVisibility(GONE);
            }
        });

        seekBarOpenReadTime.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                initSwitchBtn(5);
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
//                currentProgress = progress;
                initSwitchBtn(progress);
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    private void initSwitchBtn(int progress) {
        currentProgress = progress;
        messageViewModel.setCurrentProgress(progress);
        if(!seekBarOpenReadTime.isChecked()){
            seekBar.setThumb(null);
            readTimeTitle.setText(getContext().getString(R.string.burn_count_down_close));
            seekBar.setProgress(0);
            editText.setHint("");
            messageViewModel.setBurnAfterAfterReadSeconds(-1);
            chatReadBtn.setActivated(false);
        }else{
            chatReadBtn.setActivated(true);
            seekBar.setThumb(getResources().getDrawable(R.drawable.seekbar_thumb));
            readTimeTitle.setText(String.format(getContext().getString(R.string.msg_time_burn),progress));
            editText.setHint(String.format(getContext().getString(R.string.msg_time_delete),progress));
            messageViewModel.setBurnAfterAfterReadSeconds(progress);
        }
    }

    @OnClick(R.id.sendButton)
    void sendMessage() {
        messageEmojiCount = 0;
        Editable content = editText.getText();
        if (TextUtils.isEmpty(content)) {
            return;
        }
        List<TextEntity> textEntities = null;
        if (conversation.isSuperGroup()) {
            MentionSpan[] mentions = content.getSpans(0, content.length(), MentionSpan.class);
            if (mentions != null && mentions.length > 0) {
                textEntities = new ArrayList<>();
                for (MentionSpan span : mentions) {
                    int start = content.getSpanStart(span);
                    int end = content.getSpanEnd(span);
                    if(span.isDmType()){
                        start = start+Constants.DM_TEXT_LENGTH;
                    }
                    int length = end-start-1;
                    textEntities.add(new TextEntity(length,start,Long.valueOf(span.getUid())));
                }
            }
        }
        final String sendContent = content.toString().trim();
        int countDown = -1;
        if(chatReadBtn.isActivated()){
            countDown = currentProgress;
        }
        if(conversation.isGroupSendChat()){
            editText.setText("");
            LocalMessageInfo.setResultIntent(activity,((ConversationFragment)fragment).getGroupSendInfo(),LocalMessageInfo.buildTextLocalMessage(sendContent,countDown));
            return;
        }
        if(quoteInfo!=null){
            messageViewModel.sendTextMsg(conversation, sendContent,quoteInfo.id,textEntities,countDown);
            clearQuoteMessage();
        }else{
            messageViewModel.sendTextMsg(conversation, sendContent,0,textEntities,countDown);
        }
        editText.setText("");
    }

    public void onKeyboardShown() {
        hideEmotionLayout();
    }

    public void onKeyboardHidden() {
        // do nothing
    }

    private void setDraft() {
        if(conversation==null){
            return;
        }
        MentionSpan[] spans = editText.getText().getSpans(0, editText.getText().length(), MentionSpan.class);
        if (spans != null) {
            for (MentionSpan span : spans) {
                editText.getText().removeSpan(span);
            }
        }
        String draftStr = ChatDraftManager.getInstance().getChatDraft(conversation.id);
        if (TextUtils.isEmpty(draftStr)) {
            return;
        }
        Draft draft = Draft.fromDraftJson(draftStr);
        draftString = draft.getContent();
        messageEmojiCount = draft.getEmojiCount();
        //        int pp = draft.getBurnAfterReadPosition();
        if(currentProgress>=0){
//            choosePosition = pp;
            chatReadBtn.setActivated(currentProgress>0);
            if(currentProgress>0){
                editText.setHint(String.format(getContext().getString(R.string.msg_time_delete),currentProgress));
            }
//            messageViewModel.setBurnAfterReadPosition(choosePosition);
        }else{
            messageViewModel.setBurnAfterReadPosition(-1);
        }

        quoteInfo = draft.getQuoteInfo();
        if (quoteInfo != null) {
            refRelativeLayout.setVisibility(VISIBLE);
            refEditText.setText(UserInfo.userDisplayName(quoteInfo.sender_user_id()) + ": " + quoteInfo.toString());
        }
        if (TextUtils.isEmpty(draft.getContent())) {
            return;
        }
        SpannableStringBuilder spannableStringBuilder = new SpannableStringBuilder(draftString);
        List<Mention> mentions = draft.getMentions();
        if (mentions != null) {
            for (Mention mention : mentions) {
                if (mention.isMentionAll()) {
                    spannableStringBuilder.setSpan(new MentionSpan(true), mention.getStart(), mention.getEnd(), Spanned.SPAN_MARK_MARK);
                } else {
                    spannableStringBuilder.setSpan(new MentionSpan(mention.getUid(),mention.isDmType()), mention.getStart(), mention.getEnd(), Spanned.SPAN_MARK_MARK);
                }
            }
        }
        editText.setText(spannableStringBuilder);
//         FIXME: 4/16/21 恢复草稿时，消息列表界面会抖动，且没有滑动到最后
//        editText.requestFocus();
    }

    public void setInputText(String text) {
        if (TextUtils.isEmpty(text)) {
            return;
        }
        editText.setText(text);
        editText.setSelection(text.length());
        editText.requestFocus();
        rootLinearLayout.showSoftkey(editText);
    }

    public void onActivityPause() {
        updateConversationDraft();
    }

    private void updateConversationDraft() {
        if(conversation==null){
            return;
        }
        Editable editable = editText.getText();
        String draft = Draft.toDraftJson(editable, messageEmojiCount, 0,quoteInfo);
        ChatDraftManager.getInstance().saveDraft(conversation.id, draft);
    }

    private void showAudioButton() {
        audioButton.setVisibility(View.VISIBLE);
        audioRecorderPanel.attach(rootLinearLayout, audioButton);
        editText.setVisibility(View.GONE);
        sendButton.setVisibility(View.GONE);
        audioImageView.setVisibility(View.VISIBLE);
        audioImageView.setImageResource(R.drawable.input_icon_keyboard);
        rootLinearLayout.hideCurrentInput(editText);
        rootLinearLayout.hideAttachedInput(true);
    }


    private void hideAudioButton() {
        audioButton.setVisibility(View.GONE);
        audioRecorderPanel.deattch();
        editText.setVisibility(View.VISIBLE);
        if (TextUtils.isEmpty(editText.getText())) {
            audioImageView.setVisibility(View.VISIBLE);
            sendButton.setVisibility(View.GONE);
        } else {
            audioImageView.setVisibility(View.GONE);
            sendButton.setVisibility(View.VISIBLE);
        }
        audioImageView.setImageResource(R.drawable.input_icon_voice);
    }

    private void showEmotionLayout() {
        audioButton.setVisibility(View.GONE);
        rootLinearLayout.show(editText, emotionContainerFrameLayout);
        if (onConversationInputPanelStateChangeListener != null) {
            onConversationInputPanelStateChangeListener.onInputPanelExpanded();
        }
    }

    private void hideEmotionLayout() {
        if (onConversationInputPanelStateChangeListener != null) {
            onConversationInputPanelStateChangeListener.onInputPanelCollapsed();
        }
    }

    private void showConversationExtension() {
//        rootLinearLayout.show(editText, extContainerFrameLayout);
        rootLinearLayout.showConversationExt(editText, extContainerFrameLayout);
        if (audioButton.isShown()) {
            hideAudioButton();
        }
        if (onConversationInputPanelStateChangeListener != null) {
            onConversationInputPanelStateChangeListener.onInputPanelExpanded();
        }
    }

    private void hideConversationExtension() {
        if (onConversationInputPanelStateChangeListener != null) {
            onConversationInputPanelStateChangeListener.onInputPanelCollapsed();
        }
    }

    public void closeConversationInputPanel() {
        extension.reset();
        rootLinearLayout.hideAttachedInput(true);
        rootLinearLayout.hideCurrentInput(editText);
    }

    private void notifyTyping() {
        long now = System.currentTimeMillis();
        if (now - lastTypingTime > TYPING_INTERVAL_IN_SECOND * 1000) {
            lastTypingTime = now;
            if(conversation!=null){
                TelegramManager.getTelegramManager().sendChatAction(conversation.id);
            }
        }
    }

    @Override
    public void onEmojiSelected(String key) {
        Editable editable = editText.getText();
        if (key.equals("/DEL")) {
            messageEmojiCount--;
            messageEmojiCount = messageEmojiCount < 0 ? 0 : messageEmojiCount;
            editText.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
        } else {
            if (messageEmojiCount >= MAX_EMOJI_PER_MESSAGE) {
                Toast.makeText(activity, String.format(getContext().getString(R.string.emji_max_hint),MAX_EMOJI_PER_MESSAGE), Toast.LENGTH_SHORT).show();
                return;
            }
            messageEmojiCount++;
            int code = Integer.decode(key);
            char[] chars = Character.toChars(code);
            String value = Character.toString(chars[0]);
            for (int i = 1; i < chars.length; i++) {
                value += Character.toString(chars[i]);
            }

            int start = editText.getSelectionStart();
            int end = editText.getSelectionEnd();
            start = (start < 0 ? 0 : start);
            end = (start < 0 ? 0 : end);
            editable.replace(start, end, value);

            int editEnd = editText.getSelectionEnd();
            MoonUtils.replaceEmoticons(LQREmotionKit.getContext(), editable, 0, editable.toString().length());
            editText.setSelection(editEnd);
        }
    }
    @Override
    public void onStickerSelected(StickerInfo stickerInfo) {
        messageViewModel.sendStickerMsg(conversation, stickerInfo);
    }

    @Override
    public void onStickerRemoved(StickerInfo stickerInfo) {
        messageViewModel.removeSticker(stickerInfo);
    }

    public interface OnConversationInputPanelStateChangeListener {
        /**
         * 输入面板展开
         */
        void onInputPanelExpanded();

        /**
         * 输入面板关闭
         */
        void onInputPanelCollapsed();
    }
}
